package cloud

import (
	"encoding/json"
	"github.com/astaxie/beego/logs"
	"reflect"
	"smart_home/api/bots"
	"smart_home/api/bots/depots"
	"smart_home/api/models"
)

type DingDong struct {
	bots.BotInfo
	Intent *depots.DingDong // 意图
}

func init() {
	bots.AddBots("dingdong", new(DingDong))
}

func (c *DingDong) Init() {
	var (
		uid    string
		refVal reflect.Value
		method reflect.Value
		in     = make([]reflect.Value, 0)
		err    error
	)

	c.Intent = &depots.DingDong{}
	c.Answer = c.Intent.Answer("我还不懂您说什么")

	if err := json.Unmarshal(c.Body, c.Intent); err != nil {
		logs.Error(err)
		return
	}

	logs.Debug("%+v", c.Intent)
	if len(c.Intent.Session.User.AccessToken) == 0 {
		goto NoAuth
	}

	uid = bots.GetToken(c.Intent.Session.User.AccessToken, c.Platform)
	if len(uid) == 0 {
		goto NoAuth
	}

	if c.User, err = models.GetUserById(uid); err != nil {
		goto NoAuth
	}

	refVal = reflect.ValueOf(c)
	method = refVal.MethodByName(c.Intent.Request.Intent.Name)
	if method.IsValid() {
		method.Call(in)
	}
	return

NoAuth:
	c.Answer = c.Intent.Answer("请登陆后再操作")
	return
}

func (c *DingDong) Open() {
	answer := bots.SwitchDevice(c.User.Id, c.Intent.GetSlot("equipment").Value, true)
	if len(answer.Message) > 0 {
		c.Answer = c.Intent.Answer(answer.Message)
	}
}

func (c *DingDong) Close() {
	answer := bots.SwitchDevice(c.User.Id, c.Intent.GetSlot("equipment").Value, false)
	if len(answer.Message) > 0 {
		c.Answer = c.Intent.Answer(answer.Message)
	}
}

// 定时打开
func (c *DingDong) TimingOpen() {
	eqName := c.Intent.GetSlot("equipment").Value
	time := c.Intent.GetSlot("time").Value

	res := bots.TimingDevice(c.User.Id, eqName, time, time, true)
	if len(res.Message) > 0 {
		c.Answer = c.Intent.Answer(res.Message)
	}
}

// 定时关闭
func (c *DingDong) TimingClose() {
	eqName := c.Intent.GetSlot("equipment").Value
	time := c.Intent.GetSlot("time").Value

	res := bots.TimingDevice(c.User.Id, eqName, time, time, false)
	if len(res.Message) > 0 {
		c.Answer = c.Intent.Answer(res.Message)
	}
}
